import numpy as np
from math import sqrt

def accuracy_score(y_true,y_predict):
    assert y_true.shape[0]==y_predict.shape[0]#确保预测值与真实值特征数量相同

    return np.sum(y_true==y_predict)/len(y_true)

def mean_squared_error(y_true,y_predict):#MSE评价
    assert len(y_true)==len(y_predict)
    return np.sum((y_true-y_predict)**2)/len(y_true)

def root_mean_squared_error(y_true,y_predict):#RMSE评价
    return sqrt(mean_squared_error(y_true,y_predict))

def mean_absolute_error(y_true,y_predict):#MAE评价
    assert len(y_true)==len(y_predict)
    return np.sum(np.absolute(y_true-y_predict))/len(y_true)

def r2_score(y_true,y_predict):#R评价
    return 1-mean_squared_error(y_true,y_predict)/np.var(y_true)

"""TN"""
def TN(y_true,y_predict):#声明TN值运算
    assert len(y_true)==len(y_predict)
    return np.sum((y_true==0)&(y_predict==0))

"""FP"""
def FP(y_true,y_predict):
    assert len(y_true)==len(y_predict)
    return np.sum((y_true==0)&(y_predict==1))
"""FN"""
def FN(y_true,y_predict):
    assert len(y_true)==len(y_predict)
    return np.sum((y_true==1)&(y_predict==0))
"""TP"""
def TP(y_true,y_predict):
    assert len(y_true)==len(y_predict)
    return np.sum((y_true==1)&(y_predict==1))
"""混淆矩阵"""
def confusion_matrix(y_true,y_predict):
    return np.array([
        [TN(y_true,y_predict),FP(y_true,y_predict)],
        [FN(y_true,y_predict),TP(y_true,y_predict)]
    ])

"""精准率：precision"""
def precision_score(y_true,y_predict):
    fp=FP(y_true,y_predict)
    tp=TP(y_true,y_predict)
    try:
        return tp/(tp+fp)
    except:
        return 0.0
    
"""召回率"""
def recall_score(y_true,y_predict):
    tp=TP(y_true,y_predict)
    fn=FN(y_true,y_predict)
    try:
        return tp/(tp+fn)
    except:
        return 0.0

"""TPR"""
def TPR(y_true,y_predict):
    tp=TP(y_true,y_predict)
    fn=FN(y_true,y_predict)
    try:
        return tp/(tp+fn)
    except:
        return 0.0

"""FPR"""
def FPR(y_true,y_predict):
    fp=FP(y_true,y_predict)
    tn=TN(y_true,y_predict)
    try:
        return fp/(fp+tn)
    except:
        return 0.0